package repository.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import repository.SearchRepository;

import command.SearchForm;

import domain.SearchResultItem;
import domain.SearchResultList;
import domain.User;


@Repository
public class SearchRepositoryImpl extends AbstractHibernateRepository<SearchForm> implements SearchRepository {

	@Autowired
	public SearchRepositoryImpl(SessionFactory sessionfactory){
		super(sessionfactory);
	}

	@Override
	public void save(SearchForm searchForm) {
		super.save(searchForm);
	}

	@Override
	public List<SearchForm> getSavedSearchesByUser(User user) {
		String hql = "FROM SearchForm WHERE user=?";
		return find(hql, user);
	}

	@Override
	public SearchForm get(Integer id) {
		String hql = "FROM SearchForm WHERE id=?";
		List<SearchForm> result = find(hql, id);
		return result.isEmpty() ? null : result.get(0);
	}
	
	@Override	
	public void saveResults(SearchResultList list) {
		save(list);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SearchResultList> getSavedResultsByUser(User user) {
		return getSession().createQuery("FROM SearchResultList WHERE user=? ORDER BY name").setEntity(0, user).list();
	}
	
	@Override
	public void deleteSavedResult(SearchResultList list) {
		delete(list);
	}
	
	@Override
	public void delete(SearchForm search) {
		super.delete(search);
	}
	
	@Override
	public SearchResultList getSavedResult(int id) {
		return (SearchResultList) getSession().get(SearchResultList.class, id);
	}

	@Override
	public SearchResultItem getSavedResultItem(int id) {
		return (SearchResultItem) getSession().get(SearchResultItem.class, id);
	}
}